<?php
/*
	在线安装脚本
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
//ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_NOTICE);
@set_time_limit(0);
ob_start();
define('INSTALL',true);
define('ROOT_D', str_replace("\\",'/', dirname(__FILE__)));
if($_GET['res']) {
	$res = $_GET['res'];
	$reses = tpl_resources();
	if(array_key_exists($res, $reses)) {
		if($res == 'css') {
			header('content-type:text/css');
		} else {
			header('content-type:image/png');
		}
		echo base64_decode($reses[$res]);
		exit();
	}
}
$actions = array('license', 'env', 'db', 'finish');
$action = $_COOKIE['action'];
$action = in_array($action, $actions) ? $action : 'license';
$ispost = strtolower($_SERVER['REQUEST_METHOD']) == 'post';

if(file_exists(ROOT_D . '/core/config.php') && $action != 'finish') {
	header('location: ./index.php');
	exit;
}
header('content-type: text/html; charset=utf-8');
if($action == 'license') {
	if($ispost) {
		setcookie('action', 'env');
		header('location: ?refresh');
		exit;
	}
	tpl_install_license();
}
//服务器环境检查
if($action == 'env') {
	if($ispost) {
		setcookie('action', $_POST['do'] == 'continue' ? 'db' : 'license');
		header('location: ?refresh');
		exit;
	}
	$ret = array();
	$ret['server']['os']['value'] = php_uname();
	if(PHP_SHLIB_SUFFIX == 'dll') {
		$ret['server']['os']['remark'] = '建议使用 Linux 系统以提升程序性能';
		$ret['server']['os']['class'] = 'warning';
	}
	$ret['server']['sapi']['value'] = $_SERVER['SERVER_SOFTWARE'];
	if(PHP_SAPI == 'isapi') {
		$ret['server']['sapi']['remark'] = '建议使用 Apache 或 Nginx 以提升程序性能';
		$ret['server']['sapi']['class'] = 'warning';
	}
	$ret['server']['php']['value'] = PHP_VERSION;
	$ret['server']['dir']['value'] = ROOT_D;
	if(function_exists('disk_free_space')) {
		$ret['server']['disk']['value'] = floor(disk_free_space(ROOT_D) / (1024*1024)).'M';
	} else {
		$ret['server']['disk']['value'] = 'unknow';
	}
	$ret['server']['upload']['value'] = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknow';

	$ret['php']['version']['value'] = PHP_VERSION;
	$ret['php']['version']['class'] = 'success';
	if(version_compare(PHP_VERSION, '5.5.0') == -1) {
		$ret['php']['version']['class'] = 'danger';
		$ret['php']['version']['failed'] = true;
		$ret['php']['version']['remark'] = 'PHP版本必须为 5.5.0 以上. <a href="http://s.jinyunweb.com/">详情</a>';
	}
	if(version_compare(PHP_VERSION, '7.5.0') == 1) {
		$ret['php']['version']['class'] = 'danger';
		$ret['php']['version']['failed'] = true;
		$ret['php']['version']['remark'] = 'PHP版本必须小于 7.5.0. <a href="http://s.jinyunweb.com/">详情</a>';
	}
	$ret['php']['mysql']['ok'] = function_exists('mysqli_connect');
	if($ret['php']['mysql']['ok']) {
		$ret['php']['mysql']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
	} else {
		$ret['php']['mysql']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
	}
	
	$ret['php']['pdo']['ok'] = extension_loaded('pdo') && extension_loaded('pdo_mysql');
	if($ret['php']['pdo']['ok']) {
		$ret['php']['pdo']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['php']['pdo']['class'] = 'success';
		if(!$ret['php']['mysql']['ok']) {
			$ret['php']['pdo']['remark'] = '您的PHP环境虽然不支持 mysqli_connect, 但已经支持了PDO, 这样系统是可以正常高效运行的, 不需要额外处理. <a target="_blank" href="http://bbs.2jin1.com/forum.php?mod=redirect&goto=findpost&ptid=3564&pid=58073">详情</a>';
		}
	} else {
		if($ret['php']['mysql']['ok']) {
			$ret['php']['pdo']['value'] = '<span class="glyphicon glyphicon-remove text-warning"></span>';
			$ret['php']['pdo']['class'] = 'warning';
			$ret['php']['pdo']['remark'] = '您的PHP环境不支持PDO, 但支持 mysqli_connect, 这样系统虽然可以运行, 但还是建议你开启PDO以提升程序性能和系统稳定性. <a target="_blank" href="http://bbs.2jin1.com/forum.php?mod=redirect&goto=findpost&ptid=3564&pid=58074">详情</a>';
		} else {
			$ret['php']['pdo']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
			$ret['php']['pdo']['class'] = 'danger';
			$ret['php']['pdo']['remark'] = '您的PHP环境不支持PDO, 也不支持 mysqli_connect, 系统无法正常运行. <a target="_blank" href="http://bbs.2jin1.com/forum.php?mod=redirect&goto=findpost&ptid=3564&pid=58074">详情</a>';
			$ret['php']['pdo']['failed'] = true;
		}
	}
	
	$ret['php']['fopen']['ok'] = @ini_get('allow_url_fopen') && function_exists('fsockopen');
	if($ret['php']['fopen']['ok']) {
		$ret['php']['fopen']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
	} else {
		$ret['php']['fopen']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
	}
	
	$ret['php']['curl']['ok'] = extension_loaded('curl') && function_exists('curl_init');
	if($ret['php']['curl']['ok']) {
		$ret['php']['curl']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['php']['curl']['class'] = 'success';
		if(!$ret['php']['fopen']['ok']) {
			$ret['php']['curl']['remark'] = '您的PHP环境虽然不支持 allow_url_fopen, 但已经支持了cURL, 这样系统是可以正常高效运行的, 不需要额外处理. <a target="_blank" href="http://s.jinyunweb.com/">详情</a>';
		}
	} else {
		if($ret['php']['fopen']['ok']) {
			$ret['php']['curl']['value'] = '<span class="glyphicon glyphicon-remove text-warning"></span>';
			$ret['php']['curl']['class'] = 'warning';
			$ret['php']['curl']['remark'] = '您的PHP环境不支持cURL, 但支持 allow_url_fopen, 这样系统虽然可以运行, 但还是建议你开启cURL以提升程序性能和系统稳定性. <a target="_blank" href="http://s.jinyunweb.com/">详情</a>';
		} else {
			$ret['php']['curl']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
			$ret['php']['curl']['class'] = 'danger';
			$ret['php']['curl']['remark'] = '您的PHP环境不支持cURL, 也不支持 allow_url_fopen, 系统无法正常运行. <a target="_blank" href="http://s.jinyunweb.com/">详情</a>';
			$ret['php']['curl']['failed'] = true;
		}
	}

	$ret['php']['ssl']['ok'] = extension_loaded('openssl');
	if($ret['php']['ssl']['ok']) {
		$ret['php']['ssl']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['php']['ssl']['class'] = 'success';
	} else {
		$ret['php']['ssl']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
		$ret['php']['ssl']['class'] = 'danger';
		$ret['php']['ssl']['failed'] = true;
		$ret['php']['ssl']['remark'] = '没有启用OpenSSL, 将无法访问公众平台的接口, 系统无法正常运行. <a target="_blank" href="http://s.jinyunweb.com/">详情</a>';
	}

	$ret['php']['gd']['ok'] = extension_loaded('gd');
	if($ret['php']['gd']['ok']) {
		$ret['php']['gd']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['php']['gd']['class'] = 'success';
	} else {
		$ret['php']['gd']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
		$ret['php']['gd']['class'] = 'danger';
		$ret['php']['gd']['failed'] = true;
		$ret['php']['gd']['remark'] = '没有启用GD, 将无法正常上传和压缩图片, 系统无法正常运行. <a target="_blank" href="http://s.jinyunweb.com/">详情</a>';
	}

	$ret['php']['dom']['ok'] = class_exists('DOMDocument');
	if($ret['php']['dom']['ok']) {
		$ret['php']['dom']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['php']['dom']['class'] = 'success';
	} else {
		$ret['php']['dom']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
		$ret['php']['dom']['class'] = 'danger';
		$ret['php']['dom']['failed'] = true;
		$ret['php']['dom']['remark'] = '没有启用DOMDocument, 将无法正常安装使用模块, 系统无法正常运行. <a target="_blank" href="http://s.jinyunweb.com/">详情</a>';
	}

	$ret['write']['root']['ok'] = local_writeable(ROOT_D . '/');
	if($ret['write']['root']['ok']) {
		$ret['write']['root']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['write']['root']['class'] = 'success';
	} else {
		$ret['write']['root']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
		$ret['write']['root']['class'] = 'danger';
		$ret['write']['root']['failed'] = true;
		$ret['write']['root']['remark'] = '本地目录无法写入, 将无法使用自动更新功能, 系统无法正常运行.  <a href="http://s.jinyunweb.com/">详情</a>';
	}
	$ret['write']['data']['ok'] = local_writeable(ROOT_D . '/core');
	if($ret['write']['data']['ok']) {
		$ret['write']['data']['value'] = '<span class="glyphicon glyphicon-ok text-success"></span>';
		$ret['write']['data']['class'] = 'success';
	} else {
		$ret['write']['data']['value'] = '<span class="glyphicon glyphicon-remove text-danger"></span>';
		$ret['write']['data']['class'] = 'danger';
		$ret['write']['data']['failed'] = true;
		$ret['write']['data']['remark'] = 'core目录无法写入, 将无法写入配置文件, 系统无法正常安装. ';
	}
	
	$ret['continue'] = true;
	foreach($ret['php'] as $opt) {
		if($opt['failed']) {
			$ret['continue'] = false;
			break;
		}
	}
	if($ret['write']['failed']) {
		$ret['continue'] = false;
	}
	tpl_install_env($ret);
}
//填写数据库参数
if($action == 'db') {
	if($ispost) {
		if($_POST['do'] != 'continue') {
			setcookie('action', 'env');
			header('location: ?refresh');
			exit();
		}
		$cloud = $_POST['cloud'];
		$db = $_POST['db'];
		$user = $_POST['user'];
		$link = mysqli_connect($db['server'], $db['username'], $db['password']);
		if(empty($link)) {
			$error = mysqli_error();
			if($error){
				if (strpos($error, 'Access denied for user') !== false) {
					$error = '您的数据库访问用户名或是密码错误. <br />';
				} else {
					$error = iconv('gbk', 'utf8', $error);
				}
			}else{
				$error = '您的数据库访问异常！！';
			}
		} else {
			mysqli_query($link,"SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary");
			mysqli_query($link,"SET sql_mode=''");
			if(mysqli_errno($link)) {
				$error = mysqli_error($link);
			} else {
				$query = mysqli_query($link,"SHOW DATABASES LIKE  '{$db['name']}';");
				if (!mysqli_fetch_assoc($query)) {
					if(mysqli_get_server_info($link) > '4.1') {
						mysqli_query($link,"CREATE DATABASE IF NOT EXISTS `{$db['name']}` DEFAULT CHARACTER SET utf8");
					} else {
						mysqli_query($link,"CREATE DATABASE IF NOT EXISTS `{$db['name']}`");
					}
				}
				$query = mysqli_query($link,"SHOW DATABASES LIKE  '{$db['name']}';");
				if (!mysqli_fetch_assoc($query)) {
					$error .= "数据库不存在且创建数据库失败. <br />";
				}
				if(mysqli_errno($link)) {
					$error .= mysqli_error($link);
				}
			}
		}
		if(empty($error)) {
			//
			if($_POST['type']=='remote' && (!$cloud || !$cloud['cloudkey'] || !$cloud['secret'])){
				$error='请填写云服务参数！';
			}
		}
		if(empty($error)) {
			//检查数据库是否为空
			mysqli_select_db($link,$db['name']);
			$query = mysqli_query($link,"SHOW TABLES';");
			if (mysqli_fetch_assoc($query)) {
				$error = '您的数据库不为空，请重新建立数据库或是清空该数据库！';
			}
		}
		if(empty($error)) {
			$pieces = explode(':', $db['server']);
			$db['port'] = !empty($pieces[1]) ? $pieces[1] : '3306';
			mysqli_close($link);
			//在线下载数据
			if($_POST['type']=='remote'){
				$ins = download($cloud);
				if(empty($ins) || !is_array($ins)) {
					die('<script type="text/javascript">alert("连接不到服务器, 请稍后重试！");history.back();</script>');
				}
				if($ins['error']) {
					die('<script type="text/javascript">alert("安装失败, 错误为: ' . $ins['error'] . '！");history.back();</script>');
				}
			}else{
				$ins=array();
				$ins['config']=array(
					'authkey'=>random1(8),
					'table_pre'=>strtolower(random1(5).'_'),
					'base64_key'=>str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_'),
				);
			}
			//$ins['config']['addons']=random1(8);
			$ins['config']['resource']=trim($_POST['att'])?trim($_POST['att']):'attachment';
			$ins['sqls']=require(ROOT_D.'/core/db.php');
			$ins['data']=require(ROOT_D.'/core/data.php');
			//生成配置文件
			$config = local_config();
			$cookiepre = random1(5) . '_';
			$authkey = $ins['config']['authkey'];
			$db['table_pre']=$db['table_pre']?$db['table_pre']:'yun_';
			$config = str_replace(array(
				'{db-server}', '{db-username}', '{db-password}', '{db-port}', '{db-name}', '{db-tablepre}', '{cookiepre}', '{authkey}', '{resource}','{base64_key}'
			), array(
				$db['server'], $db['username'], $db['password'], $db['port'], $db['name'],  $db['table_pre'], $cookiepre,  $ins['config']['authkey'], $ins['config']['resource'], $ins['config']['base64_key']
			), $config);
			file_put_contents(ROOT_D . '/core/config.php', $config);
			if(!is_writable(ROOT_D)){
				exit('站点根目录无法写入，导致安装失败！');
			}
			mkdir(ROOT_D.'/'.$ins['config']['resource']);
			//@@mkdir(ROOT_D.'/'.$ins['config']['addons']);
			mkdir(ROOT_D.'/addons');
			mkdir(ROOT_D.'/'.$ins['config']['resource'].'/error_logs');
			define('BY_JYA', true);
			require ROOT_D . '/core/function/global.php';
			require ROOT_D . '/core/function/types.php';
			require ROOT_D . '/core/function/pdo.php';
			require ROOT_D . '/core/class/db.php';
			$cfg=array(
				'host'=>$db['server'],
				'username'=>$db['username'],
				'password'=>$db['password'],
				'port'=>$db['port'],
				'database'=>$db['name'],
				'tablepre'=>$db['table_pre'],
				'charset'=>'utf8',
				'pconnect'=>0,
			);
			pdo($cfg); 
			//安装数据库
			foreach($ins['sqls'] as $name=>$sql){
				$sql=str_replace("`ims_{$name}` ","`{$db['table_pre']}{$name}` ",$sql);
				pdo_query($sql);
			}
			//插入初始化数据
			if($ins['data']){
				foreach($ins['data'] as $tablename=>$tabledata){
					foreach($tabledata as $row){
						pdo_insert($tablename,$row);
					}
				}
			}
			//插入管理员数据
			$salt = random1(10);
			$password = sha1("{$user['password']}-{$salt}-{$authkey}");
			$userdata=array(
				'uniacid'=>1,
				'type'=>5,
				'name'=>$user['username'],
				'password'=>$password,
				'salt'=>$salt,
			);
			pdo_insert('core_users',$userdata);
			//插入主公众号数据
			$account=array('uniacid'=>1,'title'=>'系统','logo'=>'../core/resource/images/web-logo.jpg','token'=>random1(30),'aeskey'=>random1(43));
			pdo_insert('core_accounts',$account);
			$old_account=array('acid'=>1,'uniacid'=>1);
			pdo_insert('account_wechats',$old_account);
			//插入地图数据
			define('TABLE_PRE',$db['table_pre']);
			require ROOT_D.'/update/update_area.php';
			//安装本地插件
			/*$local_plugins=array('jy_h5game','jy_print','jy_xiu','jy_alisms','jy_alipay');
			foreach($local_plugins as $plugin_name){
				$plugin_config=ROOT_D.'/addons/'.$plugin_name.'/config.json';
				if(is_file($plugin_config)){
					$plugin_config=file_get_contents($plugin_config);
					$plugin_config=json_decode($plugin_config,true);
					if($plugin_config['install']){
						//安装数据表时，替换表前缀
						if(substr($plugin_config['install'],0,5)=='file:'){
							$install_file=ROOT_D.'/addons/'.$plugin_name.substr($plugin_config['install'],5);
							if(is_file($install_file)){
								$plugin_config['install']=file_get_contents($install_file);
							}
						}
						$plugin_config['install']=str_replace('{table_pre}',TABLE_PRE,$plugin_config['install']);
					}
					model('core/module')->plugin_install($plugin_config);
				}
			}*/
			//生成安装锁文件
			file_put_contents(ROOT_D . '/core/install.lock','');
			setcookie('action', 'finish');
			header('location: manage/index.php');
			exit();
		}
		exit($error);
	}
	tpl_install_db($error);

}
if($action == 'finish') {
	setcookie('action', '', -10);
	
	tpl_install_finish();
}

function local_writeable($dir) {
	$writeable = 0;
	if(!is_dir($dir)) {
		@mkdir($dir, 0777);
	}
	if(is_dir($dir)) {
		if($fp = fopen("$dir/test.txt", 'w')) {
			fclose($fp);
			unlink("$dir/test.txt");
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}
function local_config() {
	$cfg = <<<EOF
<?php
defined('BY_JYA') or exit('error');
if(!defined('CONFIG')){
	define('CONFIG',true);
	\$cfg = array();
	\$cfg['db']['host'] = '{db-server}';
	\$cfg['db']['username'] = '{db-username}';
	\$cfg['db']['password'] = '{db-password}';
	\$cfg['db']['port'] = '{db-port}';
	\$cfg['db']['database'] = '{db-name}';
	\$cfg['db']['charset'] = 'utf8';
	\$cfg['db']['pconnect'] = 0;
	\$cfg['db']['tablepre'] = '{db-tablepre}';

	// --------------------------  CONFIG COOKIE  --------------------------- //
	\$cfg['cookie']['pre'] = '{cookiepre}';
	\$cfg['cookie']['domain'] = '';
	\$cfg['cookie']['path'] = '/';

	// --------------------------  CONFIG SETTING  --------------------------- //
	\$cfg['setting']['charset'] = 'utf-8';
	\$cfg['setting']['cache'] = 'mysql';
	\$cfg['setting']['timezone'] = 'Asia/Shanghai';
	\$cfg['setting']['memory_limit'] = '256M';
	\$cfg['setting']['filemode'] = 0644;
	\$cfg['setting']['authkey'] = '{authkey}';
	\$cfg['setting']['founder'] = '1';
	\$cfg['setting']['development'] = 0;
	\$cfg['setting']['session_pre'] = 'byjya_';
	\$cfg['setting']['referrer'] = 0;
	\$cfg['setting']['base64_key'] = '{base64_key}';
	\$cfg['dir']['resource']='{resource}';
	// --------------------------  HTTPS UP  --------------------------- //
	\$cfg['setting']['https'] = 0;
	\$cfg['setting']['redis']['server'] = '127.0.0.1'; 
	\$cfg['setting']['redis']['port'] = 6379; 
	\$cfg['setting']['redis']['pconnect'] = 0; 
	\$cfg['setting']['redis']['requirepass'] = ''; 
	\$cfg['setting']['redis']['timeout'] = 1;
}

EOF;
	return trim($cfg);
}
function download($cloud) {
	//下载程序文件 
	if(!class_exists('ZipArchive')){
		exit('安装失败，当前PHP环境无法解压压缩包！请安装相应PHP扩展！');
	}
	$params['cloudkey']=$cloud['cloudkey'];
	$params['action']='update.install';
	$params['timestamp']=time();
	$params['sign']=get_sign1($params,$cloud['secret']);
	$url=$cloud['url']?$cloud['url']:'http://api.jinyunweb.com/api/index.php';
	$res=post($url,$params);
	$sign=substr($res,0,32);
	$res=substr($res,32);
	if($sign!=md5($res.$cloud['secret'])){
		exit('安装失败，请检查参数是否正确！错误详情：签名校验失败！');
	}
	$res=unserialize(base64_decode($res));
	if($res['type']=='error'){
		$message='安装失败，请联系进云客服！错误详情：'.$res['message'];
		exit($message);
	}
	if(!$res['files']){
		exit('安装失败，请联系进云客服！错误详情：未收到文件数据或数据传输出错。');
	}
	$temp=ROOT_D.'/temp.zip';
	copy($res['files'],$temp);
	$zip = new ZipArchive();
	$zip->open($temp);
	$zip->extractTo(ROOT_D);
	$zip->close();
	@unlink($temp);
	if(!is_dir(ROOT_D.'/custom') || !is_dir(ROOT_D.'/manage') || !is_file(ROOT_D.'/api.php')){
		exit('安装失败，请联系进云客服！错误详情：下载文件时缺失系统核心文件。');
	}
	unset($res['files']);
	return $res;
}
function get_sign1($params,$secret){
	ksort($params);
	$sign_str='';
	foreach($params as $key=>$value){
		$sign_str.=$key.$value;
	}
	$sign_str.=$secret;
	return  md5($sign_str);
}
function post($url,$params){
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$content = curl_exec($ch);
	if(curl_errno($ch)){
		$error='访问云平台失败，请联系进云客服！错误信息：'.curl_error($ch);
		exit($error);
	}
	curl_close($ch);
	
	return $content;
}
function tpl_frame() {
	global $action, $actions;
	$action = $_COOKIE['action'];
	$step = array_search($action, $actions);
	$steps = array();
	for($i = 0; $i <= $step; $i++) {
		if($i == $step) {
			$steps[$i] = ' list-group-item-info';
		} else {
			$steps[$i] = ' list-group-item-success';
		}
	}
	$progress = $step * 25 + 25;
	$content = ob_get_contents();
	ob_clean();
	$tpl = <<<EOF
<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta http-equiv="Access-Control-Allow-Origin" content="*">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>安装系统 - 进云智能生成平台</title>
		
		<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
		<link rel="stylesheet" href="//s.jinyunweb.com/core/resource/css/style.css">
		<style>
			html,body{font-size:13px;font-family:"Microsoft YaHei UI", "微软雅黑", "宋体";}
			body{
				background-color:#00c1de;
				FILTER:progid:DXImageTransform.Microsoft.Gradient(gradientType=1,startColorStr='#ffffff',endColorStr='#ff0000');
			}
			.pager li.previous a{margin-right:10px;}
			.header a{color:#FFF;}
			.header a:hover{color:#428bca;}
			.nav-tabs>li>a:hover {
				border-bottom:2px solid #fff;
			}
			.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover {
				color:#fff;
				cursor:default;
				background-color:transparent;
				border-bottom:2px solid #fff;
			}
			.progress {
				height: 8px;
				margin-bottom:20px;
				overflow:hidden;
				background-color:#f5f5f5;
				border-radius:4px;
				-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);
				box-shadow:inset 0 1px 2px rgba(0,0,0,.1);
			}
			.text-success {
				color:#fff
			}
			.alert {
				padding:10px
			}
			.h3, h3 {
				font-size: 18px;
				margin-top: 5px;
				margin-bottom: 5px;
			}
			.page-header {
				padding-bottom: 2px;
				margin: 20px 0 10px;
			}
			.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover {
					color:#fff;
					background-color:transparent;
					border-bottom:2px solid #fff;
			}
			.footer{padding:10px;}
			.footer a,.footer{color:#eee;font-size:14px;line-height:25px;}
		</style>
		<!--[if lt IE 9]>
		  <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
		  <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
		<![endif]-->
	</head>
	<body>
		<div class="container">
			<div class="header" style="margin:15px auto;">
				<ul class="nav nav-pills pull-right" role="tablist">
					<li role="presentation" class="active"><a href="javascript:;">安装进云软件</a></li>
					<li role="presentation"><a href="http://s.jinyunweb.com" target="_blank">应用市场</a></li>
				</ul>
				<img src="//bbs.jinyunweb.com/static/image/common/top-logo.png" />
			</div>
			<div class="row" style="margin:auto 60px;text-align:right;color:#fff">
				<div class="col-lg-3" style="padding:0">
					<h5>许可协议</h5>
				</div>
				<div class="col-lg-3" style="padding:0">
					<h5>环境监测</h5>
				</div>
				<div class="col-lg-3" style="padding:0">
					<h5>参数配置</h5>
				</div>
				<div class="col-lg-3" style="padding:0">
					<h5>安装成功</h5>
				</div>
			</div>
			<div class="row" style="margin:auto 60px;">
			<div class="progress" title="安装进度">
						<div class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" aria-valuenow="{$progress}" aria-valuemin="0" aria-valuemax="100" style="width: {$progress}%;">
						</div>
				</div>
			</div>
			<div class="row" style="margin:auto 60px;">
					{$content}
			</div>
			<div class="row" style="margin:15px auto; color:#fff">
				<div class="text-center">
					<a href="http://s.jinyunweb.com" target="_blank">应用市场</a> &nbsp; &nbsp; 
					<a href="http://bbs.jinyunweb.com" target="_blank">进云论坛</a> &nbsp; &nbsp; 
				</div>
				<div class="text-center">
					Powered by <a href="http://www.jinyunweb.com"><b>进云科技</b></a> v1.0.1
				</div>
			</div>
		</div>
		<script type="text/javascript" src="//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
		<script type="text/javascript" src="//apps.bdimg.com/libs/bootstrap/3.3.4/js/bootstrap.min.js"></script>
	</body>
</html>
EOF;
	echo trim($tpl);
}

function tpl_install_license() {
	echo <<<EOF
		<div style="color:#fff;FILTER:progid:DXImageTransform.Microsoft.Gradient(gradientType=1,startColorStr='#ffffff',endColorStr='#ff0000');">
			<div class="panel-body" style="overflow-y:scroll;max-height:300px;line-height:20px;margin-top:20px;scrollbar-base-color:#fff;">
				<h4>版权所有 (c)2014-2019，进云团队保留所有权利。 </h4>
				<p>
					感谢您选择进云 - 智能生成系统（以下简称进云，进云基于 PHP + MySQL的技术开发） <br />
					为了使你正确并合法的使用本软件，请你在使用前务必阅读清楚下面的协议条款：
				</p>
				<p>
					<strong>一、本授权协议适用且仅适用于进云系统(进云. 以下简称进云)任何版本，进云官方对本授权协议的最终解释权。</strong>
				</p>
				<p>
					<strong>二、协议许可的权利 </strong>
					<ol>
						<li>您可以在完全遵守本最终用户授权协议的基础上，将本软件应用于非商业用途，而不必支付软件版权授权费用。</li>
						<li>您可以在协议规定的约束和限制范围内修改进云源代码或界面风格以适应您的网站要求。</li>
						<li>您拥有使用本软件构建的网站全部内容所有权，并独立承担与这些内容的相关法律义务。</li>
						<li>获得商业授权之后，您可以将本软件应用于商业用途，同时依据所购买的授权类型中确定的技术支持内容，自购买时刻起，在技术支持期限内拥有通过指定的方式获得指定范围内的技术支持服务。商业授权用户享有反映和提出意见的权力，相关意见将被作为首要考虑，但没有一定被采纳的承诺或保证。</li>
					</ol>
				</p>
				<p>
					<strong>三、协议规定的约束和限制 </strong>
					<ol>
						<li>未获商业授权之前，不得将本软件用于商业用途（包括但不限于企业网站、经营性网站、以营利为目的或实现盈利的网站）。</li>
						<li>未经官方许可，不得对本软件或与之关联的商业授权进行出租、出售、抵押或发放子许可证。</li>
						<li>未经官方许可，禁止在进云的整体或任何部分基础上以发展任何派生版本、修改版本或第三方版本用于重新分发。</li>
						<li>如果您未能遵守本协议的条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。</li>
					</ol>
				</p>
				<p>
					<strong>四、有限担保和免责声明 </strong>
					<ol>
						<li>本软件及所附带的文件是作为不提供任何明确的或隐含的赔偿或担保的形式提供的。</li>
						<li>用户出于自愿而使用本软件，您必须了解使用本软件的风险，在尚未购买产品技术服务之前，我们不承诺对免费用户提供任何形式的技术支持、使用担保，也不承担任何因使用本软件而产生问题的相关责任。</li>
						<li>电子文本形式的授权协议如同双方书面签署的协议一样，具有完全的和等同的法律效力。您一旦开始确认本协议并安装  进云，即被视为完全理解并接受本协议的各项条款，在享有上述条款授予的权力的同时，受到相关的约束和限制。协议许可范围以外的行为，将直接违反本授权协议并构成侵权，我们有权随时终止授权，责令停止损害，并保留追究相关责任的权力。</li>
						<li>如果本软件带有其它软件的整合API示范例子包/接口包，这些文件版权不属于本软件官方，并且这些文件是没经过授权发布的，请参考相关软件的使用许可合法的使用。</li>
					</ol>
				</p>
			</div>
		</div>
		<form class="form-inline" role="form" method="post">
			<ul class="pager">
				<li class="pull-left" style="display:block;padding:5px 10px 5px 0;">
					<div class="checkbox-inline" style="padding-top:0px;margin-left:18px;color:#fff">
						<label>
							<input type="checkbox"> 我已经阅读并同意此协议
						</label>
					</div>
				</li>
				<li class="previous" style="color:#28b0e4" ><a href="javascript:;" onclick="if(jQuery(':checkbox:checked').length == 1){jQuery('form')[0].submit();}else{alert('您必须同意软件许可协议才能安装！')};">继续 >></a></li>
			</ul>
		</form>
EOF;
	tpl_frame();
}

function tpl_install_env($ret = array()) {
	if(empty($ret['continue'])) {
		$continue = '<li class="previous disabled" style="color:#28b0e4"><a href="javascript:;">请先解决环境问题后继续</a></li>';
	} else {
		$continue = '<li class="previous" style="color:#28b0e4"><a href="javascript:;" onclick="$(\'#do\').val(\'continue\');$(\'form\')[0].submit();">继续 >></li>';
	}
	echo <<<EOF
		<div class="" style="color:#fff">
			<div class="page-header" >
				<h3>服务器信息</h3>
			 </div>
			<table class="table table-striped" style="background-color:transparent">
				<tr style="background-color:transparent">
					<th style="width:150px;background-color:transparent">参数</th>
					<th style="background-color:transparent">值</th>
					<th style="background-color:transparent"></th>
				</tr>
				<tr class="{$ret['server']['os']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">服务器操作系统</td>
					<td style="background-color:transparent">{$ret['server']['os']['value']}</td>
					<td style="background-color:transparent">{$ret['server']['os']['remark']}</td>
				</tr>
				<tr class="{$ret['server']['sapi']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">Web服务器环境</td>
					<td style="background-color:transparent">{$ret['server']['sapi']['value']}</td>
					<td style="background-color:transparent">{$ret['server']['sapi']['remark']}</td>
				</tr>
				<tr class="{$ret['server']['php']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">PHP版本</td>
					<td style="background-color:transparent">{$ret['server']['php']['value']}</td>
					<td style="background-color:transparent">{$ret['server']['php']['remark']}</td>
				</tr>
				<tr class="{$ret['server']['dir']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">程序安装目录</td>
					<td style="background-color:transparent">{$ret['server']['dir']['value']}</td>
					<td style="background-color:transparent">{$ret['server']['dir']['remark']}</td>
				</tr>
				<tr class="{$ret['server']['disk']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">磁盘空间</td>
					<td style="background-color:transparent">{$ret['server']['disk']['value']}</td>
					<td style="background-color:transparent">{$ret['server']['disk']['remark']}</td>
				</tr>
				<tr class="{$ret['server']['upload']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">上传限制</td>
					<td style="background-color:transparent">{$ret['server']['upload']['value']}</td>
					<td style="background-color:transparent">{$ret['server']['upload']['remark']}</td>
				</tr>
			</table>
		</div>

		<div class="alert alert-warning">PHP环境要求必须满足下列所有条件，否则系统或系统部份功能将无法使用。</div>
		<div class="" style="color:#fff">
			<div class="page-header" >
				<h3>PHP环境要求</h3>
			 </div>
			<table class="table table-striped">
				<tr style="background-color:transparent">
					<th style="width:150px;background-color:transparent">选项</th>
					<th style="width:180px;background-color:transparent">要求</th>
					<th style="width:50px;background-color:transparent">状态</th>
					<th style="background-color:transparent">说明及帮助</th>
				</tr>
				<tr class="{$ret['php']['version']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">PHP版本</td>
					<td style="background-color:transparent">5.5或者5.5以上</td>
					<td style="background-color:transparent">{$ret['php']['version']['value']}</td>
					<td style="background-color:transparent;color:red">{$ret['php']['version']['remark']}</td>
				</tr>
				<tr class="{$ret['php']['pdo']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">MySQL</td>
					<td style="background-color:transparent">支持(建议支持PDO)</td>
					<td style="background-color:transparent">{$ret['php']['mysql']['value']}</td>
					<td rowspan="2" style="background-color:transparent;color:red">{$ret['php']['pdo']['remark']}</td>
				</tr>
				<tr class="{$ret['php']['pdo']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">PDO_MYSQL</td>
					<td style="background-color:transparent">支持(强烈建议支持)</td>
					<td style="background-color:transparent;color:red">{$ret['php']['pdo']['value']}</td>
				</tr>
				<tr class="{$ret['php']['curl']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">allow_url_fopen</td>
					<td style="background-color:transparent">支持(建议支持cURL)</td>
					<td style="background-color:transparent">{$ret['php']['fopen']['value']}</td>
					<td rowspan="2" style="background-color:transparent;color:red">{$ret['php']['curl']['remark']}</td>
				</tr>
				<tr class="{$ret['php']['curl']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">cURL</td>
					<td style="background-color:transparent">支持(强烈建议支持)</td>
					<td style="background-color:transparent;color:red">{$ret['php']['curl']['value']}</td>
				</tr>
				<tr class="{$ret['php']['ssl']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">openSSL</td>
					<td style="background-color:transparent">支持</td>
					<td style="background-color:transparent">{$ret['php']['ssl']['value']}</td>
					<td style="background-color:transparent;color:red">{$ret['php']['ssl']['remark']}</td>
				</tr>
				<tr class="{$ret['php']['gd']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">GD2</td>
					<td style="background-color:transparent">支持</td>
					<td style="background-color:transparent">{$ret['php']['gd']['value']}</td>
					<td  style="background-color:transparent;color:red">{$ret['php']['gd']['remark']}</td>
				</tr>
				<tr class="{$ret['php']['dom']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">DOM</td>
					<td style="background-color:transparent">支持</td>
					<td style="background-color:transparent">{$ret['php']['dom']['value']}</td>
					<td style="background-color:transparent;color:red">{$ret['php']['dom']['remark']}</td>
				</tr>
			</table>
		</div>

		<div class="alert alert-warning">系统要求进云整个安装目录必须可写, 才能使用进云所有功能。</div>
		<div class="" style="color:#fff">
			<div class="page-header" >
				<h3>目录权限监测</h3>
			 </div>
			<table class="table table-striped">
				<tr style="background-color:transparent">
					<th style="width:150px;background-color:transparent">目录</th>
					<th style="width:180px;background-color:transparent">要求</th>
					<th style="width:50px;background-color:transparent">状态</th>
					<th style="background-color:transparent">说明及帮助</th>
				</tr>
				<tr class="{$ret['write']['root']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">/</td>
					<td style="background-color:transparent">整目录可写</td>
					<td style="background-color:transparent">{$ret['write']['root']['value']}</td>
					<tdv>{$ret['write']['root']['remark']}</td>
				</tr>
				<tr class="{$ret['write']['data']['class']}" style="background-color:transparent">
					<td style="background-color:transparent">/</td>
					<td style="background-color:transparent">core目录可写</td>
					<td style="background-color:transparent">{$ret['write']['data']['value']}</td>
					<td style="background-color:transparent">{$ret['write']['data']['remark']}</td>
				</tr>
			</table>
		</div>
		<form class="form-inline" role="form" method="post">
			<input type="hidden" name="do" id="do" />
			<ul class="pager">
				<li class="previous" style="color:#28b0e4"><a href="javascript:;" onclick="$('#do').val('back');$('form')[0].submit();"> << 返回</a></li>
				{$continue}
			</ul>
		</form>
EOF;
	tpl_frame();
}

function tpl_install_db($error = '') {
	if(!empty($error)) {
		$message = '<div class="alert alert-danger">发生错误: ' . $error . '</div>';
	}
	$insTypes = array();
	if(file_exists(ROOT_D . '/index.php') && is_dir(ROOT_D . '/custom') && is_dir(ROOT_D . '/manage')) {
		$insTypes['local'] = ' checked="checked"';
		$show_cloud='none';
	} else {
		$insTypes['remote'] = ' checked="checked"';
		$show_cloud='block';
	}
	if (!empty($_POST['type'])) {
		$insTypes = array();
		$insTypes[$_POST['type']] = ' checked="checked"';
	}
	$disabled = ' disabled="disabled"';
	echo <<<EOF
	{$message}
	<form class="form-horizontal" method="post" role="form">
		<div class="" style="color:#fff">
			<div class="page-header" >
				<h3>安装选项</h3>
			 </div>
			<div class="panel-body">
				<div class="form-group">
					<label class="col-sm-2 control-label">安装方式</label>
					<div class="col-sm-10">
						<label class="radio-inline" style="color:#fff;display:{$show_cloud};" >
							<input type="radio" name="type" value="remote"{$insTypes['remote']}> 在线安装
						</label>
						<label class="radio-inline" style="color:#fff">
							<input type="radio" name="type" value="local"{$insTypes['local']}> 本地安装
						</label>
						<div class="help-block">
							
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="" style="color:#fff">
			<div class="page-header" >
				<h3>数据库选项</h3>
			 </div>
			<div class="panel-body">
				<div class="form-group">
					<label class="col-sm-2 control-label">数据库主机</label>
					<div class="col-sm-4">
						<input class="form-control" type="text" name="db[server]" value="127.0.0.1">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">数据库用户</label>
					<div class="col-sm-4">
						<input class="form-control" type="text" name="db[username]" value="root">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">数据库密码</label>
					<div class="col-sm-4">
						<input class="form-control" type="text" name="db[password]">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">数据库名称</label>
					<div class="col-sm-4">
						<input class="form-control" type="text" name="db[name]" value="jinyun">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">数据表前缀</label>
					<div class="col-sm-4">
						<input class="form-control" type="text" name="db[table_pre]" value="yun_">
					</div>
				</div>
				
			</div>
		</div>
		<div class="" style="color:#fff" style="display:{$show_cloud}">
			<div class="page-header" >
				<h3>云服务选项（本地安装可不填写）</h3>
			 </div>
			 <div class="panel-body">
				<div class="form-group">
					<label class="col-sm-2 control-label">云平台token</label>
					<div class="col-sm-4">
						<input class="form-control" data-type="cloud" type="text" name="cloud[cloudkey]">
						<div class="help-block">注册云服务：<a href="http://s.jinyunweb.com/manage/index.php?plugin=core&action=user.register" style="color:#f60" target="_blank">http://s.jinyunweb.com</a></div>
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">云平台密钥</label>
					<div class="col-sm-4">
						<input class="form-control" data-type="cloud" type="text" name="cloud[secret]">
					</div>
				</div>
			</div>
		</div>
		<div class="" style="color:#fff">
			<div class="page-header" >
				<h3>管理选项</h3>
			 </div>
			<div class="panel-body">
				<div class="form-group">
					<label class="col-sm-2 control-label">指定系统附件目录</label>
					<div class="col-sm-4">
						<input class="form-control" type="text" name="att" value="attachment">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">管理员账号</label>
					<div class="col-sm-4">
						<input class="form-control" type="username" name="user[username]">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">管理员密码</label>
					<div class="col-sm-4">
						<input class="form-control" type="password" name="user[password]">
					</div>
				</div>
				<div class="form-group">
					<label class="col-sm-2 control-label">确认密码</label>
					<div class="col-sm-4">
						<input class="form-control" type="password"">
					</div>
				</div>
				
			</div>
		</div>
		<input type="hidden" name="do" id="do" />
		<ul class="pager">
			<li class="previous" style="color:#28b0e4"><a href="javascript:;" onclick="$('#do').val('back');$('form')[0].submit();"><< 返回</a></li>
			<li class="previous" style="color:#28b0e4"><a href="javascript:;" onclick="if(check(this)){jQuery('#do').val('continue');$('form')[0].submit();}">继续 >></a></li>
		</ul>
	</form>
	<script>
		var lock = false;
		function check(obj) {
			if(lock) {
				return;
			}
			$('.form-control').parent().parent().removeClass('has-error');
			var error = false;
			$('.form-control').each(function(){
				if($(this).val() == '') {
					if($(this).attr('data-type')!='cloud'){
						$(this).parent().parent().addClass('has-error');
						this.focus();
						error = true;
					}
					
				}
			});
			if(error) {
				alert('请检查未填项');
				return false;
			}
			if($(':password').eq(0).val() != $(':password').eq(1).val()) {
				$(':password').parent().parent().addClass('has-error');
				alert('确认密码不正确.');
				return false;
			}
			lock = true;
			$(obj).parent().addClass('disabled');
			$(obj).html('正在执行安装');
			return true;
		}
	</script>
EOF;
	tpl_frame();
}

function tpl_install_finish() {
	echo <<<EOF
	<div class="page-header" style="color:#fff"><h3>安装完成</h3></div>
	<div class="alert alert-success">
		恭喜您!已成功安装“进云-智能生成”系统，您现在可以: <a target="_blank" class="btn btn-success" href="./manage/index.php">访问网站首页</a>
		<br />
	</div>
EOF;
	tpl_frame();
}

function tpl_resources() {
	static $res = array(
		'logo' => '//bbs.jinyunweb.com/static/image/common/top-logo.png',
	);
	return $res;
}
function random1($length, $numeric = FALSE){
	$str='1234567890QWERTYUIOPASDFGHJKLZXCVBNMzxcvbnmqwertyuiopasdfghjkl';
	$result='';
	for($i=0;$i<$length;$i++){
		if($numeric){
			$j=mt_rand(0,9);
		}else{
			$j=mt_rand(0,61);
		}
		$result.=$str[$j];
	}
	return $result;
}
